| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- import { pick } from "lodash";
- import { NextResponse } from "next/server";
- import { WLEDClient } from "wled-client";
- import automation from "data/automation.json";
- const get = (url) => {
- // console.log("get", url);
- return fetch(url, { cache: "no-store" })
- .then((resp) => resp && resp.text())
- .then((result) => result);
- };
- const post = (url, value) => {
- // console.log("post", url, JSON.stringify(value));
- return fetch(url, {
- method: "POST",
- cache: "no-store",
- headers: {
- Accept: "application/json",
- "Content-Type": "application/json"
- },
- body: JSON.stringify(value)
- })
- .then((resp) => resp && resp.json())
- .then((result) => result);
- };
- // const update = async (client, { ps, ...value }) => {
- // console.log("update", client, JSON.stringify(value));
- // let url = `http://${client}/json/state`;
- // if (ps) {
- // await post(url, { ps: ps, v: true });
- // await sleep(1000);
- // }
- // let resp = await post(url, { ...value, v: true });
- // // console.log("->", "resp", resp);
- // let result = pick(resp, ["ps", ...Object.keys(value)]);
- // console.log("->", result);
- // return result;
- // };
- const update = ({ id, client, on, bri, ...rest }) => {
- let url = `http://${client}/win`;
- if (id) url += `&PL=${id}`;
- if (on) url += `&T=1`;
- else url += `&T=0`;
- if (bri) url += `&A=${bri}`;
- return get(url)
- .then((_) => ({
- ps: id,
- on: on,
- bri: bri
- }))
- .catch((err) => ({ error: err.message }));
- };
- const action = async ({ id, client, on, ...rest }) => {
- let wled = new WLEDClient(client); // setup a connection to the client
- // await wled.init(); // init the connection
- await wled.setPreset(id); // set the preset
- if (on) await wled.turnOn(); // turn off the lights
- else await wled.turnOff(); // turn off the lights
- await wled.refreshState();
- return {
- ...pick(wled?.state || {}, ["on", "brightness", "presetId"])
- };
- };
- export async function GET(req, { params }) {
- let promises = [];
- let id = params?.id || null;
- try {
- if (!id) throw new Error("No id specified");
- let clients = (automation?.[id] && Object.keys(automation?.[id])) || [];
- if (!clients) throw new Error("No clients fowr id", id);
- for (let client of clients) {
- promises.push(update({ id, client, ...automation?.[id]?.[client] }));
- }
- } catch (err) {
- return NextResponse.json({ error: err?.message }, { status: 500 });
- }
- return Promise.allSettled(promises)
- .then((results) => {
- return NextResponse.json(results?.map((o) => o?.value));
- })
- .catch((err) => {
- return NextResponse.json({ error: err?.message }, { status: 500 });
- });
- }
|